<?php
namespace App\Services\Wxxcx;

use App\Services\BaseService as Service;
use Illuminate\Support\Facades\DB;

class TmpService extends BaseService
{
    /**
     * 个人业务
     */

    /**
     * 列表
     * @param array $pages【start，limit】
     * @param array $pas【scene_id】
     */
    public function getList($pages, $pas)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbTmp)->where('del', 1);
        if (isset($pas['uid']) && $pas['uid']) {
            $db = $db->where('uid', $pas['uid']);
        }
        if (isset($pas['scene_id']) && $pas['scene_id']) {
            $db = $db->where('scene_id', $pas['scene_id']);
        }
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $dayStart = date('Y-m-d', time()).' 00:00:01';
        $dayEnd = date('Y-m-d', time()).' 23:59:59';
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $sceneOne = (array) $this->dbConn($this->dbScene)
                ->where('id', $v['scene_id'])
                ->first();
            $visitTotal = $this->dbConn($this->dbQrlog)
                ->where('tmp_id', $v['id'])
                ->where('addtime', '>=', $dayStart)
                ->where('addtime', '<=', $dayEnd)
                ->count();
            $visitNum = $this->dbConn($this->dbQrlog)
                ->where('tmp_id', $v['id'])
                ->where('addtime', '>=', $dayStart)
                ->where('addtime', '<=', $dayEnd)
                ->count();
            $ts = $v['uptime'] ? explode(' ', $v['uptime'])[0] : '-';
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'code' => $v['code'],
                'scene_name' => empty($sceneOne) ? '-' : $sceneOne['title'],
                'describe' => $v['describe'],
                'prefixUrl' => env('DOMAIN').'/',
                'thumb' => file_exists($v['thumb']) ? $v['thumb'] : '',
                'lasttime' => $ts,
                'visit_total' => $visitTotal,
                'visit_num' => $visitNum,
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 是否存在
     */
    public function exist($code)
    {
        return (array) $this->dbConn($this->dbTmp)
            ->where('del', 1)
            ->where('code', $code)
            ->first();
    }

    /**
     * 详情
     * @param string $code
     */
    public function getOne($code)
    {
        $res = (array) $this->dbConn($this->dbTmp)
            ->where('code', $code)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        };
        $codeOne = (array) $this->dbConn($this->dbQr)
            ->where('code', $code)
            ->first();
        $visit_total = $this->dbConn($this->dbQrlog)
            ->where('code', $code)
            ->count('id');
        //属性集合
        $attrList = $this->dbConn($this->dbTmpAttr)
            ->select('id', 'attr_name as attr_key', 'val as attr_val')
            ->where('del', 1)
            ->where('tmp_id', $res['id'])
            ->get();
        //关注集合
        $followTotal = $this->dbConn($this->dbTmpFollow)
            ->where('del', 1)
            ->where('tmp_id', $res['id'])
            ->count();
        $followOnes = $this->dbConn($this->dbTmpFollow)
            ->select('uid', 'addtime')
            ->where('del', 1)
            ->where('tmp_id', $res['id'])
            ->skip(0)->take(5)
            ->get();
        $followList = [];
        if (count($followOnes)) {
            foreach ($followOnes as $fo) {
                $fo= (array) $fo;
                $addtimes = explode(' ', $fo['addtime']);
                $followList[] = [
                    'uid' => $fo['uid'],
                    'addtime' => $addtimes[0],
                ];
            }
        }
        //回复集合
        $replyTotal = $this->dbConn($this->dbTmpReply)
            ->where('del', 1)
            ->where('tmp_id', $res['id'])
            ->count();
        $replyOnes = $this->dbConn($this->dbTmpReply)
            ->select('uid', 'cnt', 'addtime')
            ->where('del', 1)
            ->where('tmp_id', $res['id'])
            ->get();
        $replyList = [];
        if (count($replyOnes)) {
            foreach ($replyOnes as $ro) {
                $ro = (array) $ro;
                $addtimes = explode(' ', $ro['addtime']);
                $replyList[] = [
                    'uid' => $ro['uid'],
                    'addtime' => $addtimes[0],
                ];
            }
        }
        $arys = [
            'id' => $res['id'],
            'title' => $res['title'],
            'describe' => $res['describe'],
            'code' => $res['code'],
            'show_code' => $codeOne['show_code'],
            'prefixUrl' => env('DOMAIN').'/',
            'thumb' => file_exists($res['thumb']) ? $res['thumb'] : '',
            'visit_total' => $visit_total,
            'lasttime' => $res['uptime'],
            'attrList' => $attrList,
            'follow_total' => $followTotal,
            'followList' => $followList,
            'reply_total' => $replyTotal,
            'replyList' => $replyList,
        ];
        return $this->toback(0, '', $arys);
    }

    /**
     * 添加
     * @param array $pas【uid、code、title、describe】
     */
    public function add($pas)
    {
        DB::beginTransaction(); //开启事务
        try {
            //模板更新
            $pas['addtime'] = $pas['uptime'] = toDate();
            $lastid = $this->dbConn($this->dbTmp)->insertGetId($pas);
            if (!$lastid) {
                return $this->toback(-1, 'error');
            }
            //码更新
            $this->dbConn($this->dbQr)->where('code', $pas['code'])
                ->update(['tmp_id' => $lastid, 'usetime' => toDate()]);
//            //扫码日志
//            $logData = [
//                'uid' => $pas['uid'],
//                'code' => $pas['code'],
//                'client_type' => 2,
//                'errMsg' => '物品添加成功',
//                'tmp_id' => $lastid,
//                'addtime' => toDate(),
//            ];
//            $this->dbConn($this->dbQrlog)->insertGetId($logData);
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success', 'data'=>$lastid);
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code'=>-1, 'msg'=>'操作失败');
        }
    }

    /**
     * 上传封面图
     * @param int $id
     * @param string $thumb
     */
    public function uploadThumb($id, $thumb)
    {
        $res = (array) $this->dbConn($this->dbTmp)->where('id', $id)->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        if (file_exists($res['thumb'])) {
            unlink($res['thumb']);
        }
        $this->dbConn($this->dbTmp)->where('id', $id)->update(['thumb' => $thumb]);
        return $this->toback();
    }

    /**
     * 修改
     * @param int $id
     * @param array $pas【title、describe】
     */
    public function modify($id, $pas)
    {
        $pas['uptime'] = toDate();
        $up = $this->dbConn($this->dbTmp)->where('id', $id)->update($pas);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 属性更新
     * @param int $attrid
     * @param array $pas【tmp_id、attr_name、val】
     */
    public function attrModify($attrid, $pas)
    {
        if (!$attrid) {
            $res = (array) $this->dbConn($this->dbTmpAttr)
                ->where('del', 1)
                ->where('attr_name', $pas['attr_name'])
                ->first();
            if (!empty($res)) {
                return $this->toback(-2, '已存在');
            }
            $pas['addtime'] = $pas['uptime'] = toDate();
            $lastid =  $this->dbConn($this->dbTmpAttr)->insertGetId($pas);
            if (!$lastid) {
                return $this->toback(-1, 'error');
            }
        } else {
            $res = (array) $this->dbConn($this->dbTmpAttr)
                ->where('del', 1)
                ->where('id', $attrid)
                ->first();
            if (empty($res)) {
                return $this->toback(-2, '没有记录');
            }
            $pas['uptime'] = toDate();
            $up = $this->dbConn($this->dbTmpAttr)
                ->where('id', $attrid)
                ->update($pas);
            if (!$up) {
                return $this->toback(-1, 'error');
            }
        }
        return $this->toback();
    }

    /**
     * 属性删除
     * @param int $attrid
     */
    public function attrDel($attrid)
    {
        $res = (array) $this->dbConn($this->dbTmpAttr)
            ->where('del', 1)
            ->where('id', $attrid)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $up = $this->dbConn($this->dbTmpAttr)
            ->where('id', $attrid)
            ->update(['del' => 2, 'deltime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }
}